import { createApp } from "vue";
import { createRouter, createWebHistory } from 'vue-router';
import App from "./App.vue";
import { defaultRouterList, setupAuthGuard } from "./router";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import "element-plus/theme-chalk/dark/css-vars.css";
// 引入平滑交互样式（Ant Design Pro 标准）
import "./styles/smooth-interactions.scss";
import "./styles/index.css";
import "./styles/theme/element-dark.scss";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import startQiankun, { globalState, messageService } from './micro';

// 等待容器元素渲染完成（使用 MutationObserver，提高可靠性）
const waitForContainer = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    // 先声明所有变量
    let observer: MutationObserver | null = null;
    let intervalId: any = null;
    let timeoutId: any = null;

    const cleanup = () => {
      if (observer) observer.disconnect();
      if (intervalId) clearInterval(intervalId);
      if (timeoutId) clearTimeout(timeoutId);
    };

    const found = () => {
      console.log('[MicroFrontendMain] 微应用容器已找到');
      cleanup();
      resolve();
    };

    // 立即检查一次
    if (document.getElementById('micro-container')) {
      return found();
    }

    // 监听 DOM 变化
    observer = new MutationObserver(() => {
      if (document.getElementById('micro-container')) {
        found();
      }
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // 延时轮询，兜底（菜单加载/布局切换可能延迟）
    intervalId = setInterval(() => {
      if (document.getElementById('micro-container')) {
        found();
      }
    }, 200);

    // 超时兜底（加长到 15s）
    timeoutId = setTimeout(() => {
      cleanup();
      reject(new Error('等待微应用容器超时'));
    }, 15000);
  });
};

// 配置NProgress
NProgress.configure({ 
  easing: 'ease',
  speed: 500,
  showSpinner: false,
  trickleSpeed: 200,
  minimum: 0.3
});

// 创建pinia实例
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

// 声明全局变量用于微应用生命周期
let app: any = null;
let router: any = null;
let history: any = null;

// 创建实例（用于独立运行模式）
const standaloneApp = createApp(App);
standaloneApp.use(pinia);
standaloneApp.use(ElementPlus, { locale: zhCn });

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  standaloneApp.component(key, component);
}

// 声明 qiankun 全局变量
declare global {
  interface Window {
    __POWERED_BY_QIANKUN__?: boolean;
    bootstrap?: typeof bootstrap;
    mount?: typeof mount;
    unmount?: typeof unmount;
    mainAppGlobalState?: {
      token?: string;
      user?: any;
      isLogin?: boolean;
    };
    startQiankunWhenReady?: () => Promise<void>;
  }
}

// 全局状态存储，供跨窗口通信使用
window.mainAppGlobalState = {
  token: undefined,
  user: undefined,
  isLogin: false,
};

// 微应用生命周期钩子
export async function bootstrap() {
  console.log('[MicroFrontendMain] bootstraped');
}

export async function mount(props: any) {
  console.log('🚨 [MicroFrontendMain] =====  MOUNT 函数开始执行 =====');
  console.log('[MicroFrontendMain] mount() called with props:', props);
  console.log('[MicroFrontendMain] 检查DOM状态:', {
    body: !!document.body,
    container: !!document.getElementById('micro-frontend-main-app'),
    readyState: document.readyState,
  });

  // 为独立模式设置默认的全局状态
  if (!props || !props.globalState) {
    console.log('[MicroFrontendMain] 独立模式运行，设置默认的全局状态');
    window.mainAppGlobalState = {
      token: 'mock-token-for-local-development',
      user: {
        userId: 1,
        userName: '管理员',
        roles: ['admin'],
        permissions: ['*:*:*'],
      },
      isLogin: true,
    };
  } else {
    console.log('[MicroFrontendMain] 在qiankun环境中运行，使用传入的全局状态');
  }

  try {
    // 创建路由实例
    console.log('🗺️ [MicroFrontendMain] 开始创建路由实例...');
    console.log('[MicroFrontendMain] routerBase:', props?.routerBase || '/');

    const localHistory = createWebHistory(props?.routerBase || '/');
    const localRouter = createRouter({
      history: localHistory,
      routes: defaultRouterList,
    });

    // 🆕 关键：立即设置认证守卫
    setupAuthGuard(localRouter);
    console.log('✅ [MicroFrontendMain] 认证守卫已设置');

    history = localHistory;
    router = localRouter;

    console.log('✅ [MicroFrontendMain] 路由实例创建成功:', router);

    // 创建应用实例
    console.log('🎨 [MicroFrontendMain] 开始创建 Vue 应用实例...');
    const localApp = createApp(App);
    console.log('✅ [MicroFrontendMain] Vue 应用实例创建成功:', localApp);

    // 配置应用
    localApp.use(pinia);
    console.log('[MicroFrontendMain] Pinia store initialized successfully');
    localApp.use(router);
    localApp.use(ElementPlus, { locale: zhCn });

    // 注册所有图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      localApp.component(key, component);
    }

    // 注入全局属性用于与其他微应用通信
    if (props?.getGlobalState) {
      localApp.config.globalProperties.$getGlobalState = props.getGlobalState;
    }

    if (props?.setGlobalState) {
      localApp.config.globalProperties.$setGlobalState = props.setGlobalState;
    }

    // 注入消息服务
    if (props?.messageService) {
      localApp.config.globalProperties.$messageService = props.messageService;
    }

    // 挂载应用
    let container;

    if (props?.container) {
      // 微前端模式下的容器
      if (typeof props.container === 'string') {
        container = document.querySelector(props.container);
      } else if (props.container.querySelector) {
        container = props.container.querySelector('#micro-frontend-main-app') || props.container;
      } else {
        container = props.container;
      }
    }

    // 如果微前端模式没有找到合适容器，或者在独立模式下，按优先级查找
    if (!container) {
      container = document.getElementById('micro-frontend-main-app') || document.querySelector('#app') || document.body;
    }

    console.log('🎨 [MicroFrontendMain] 准备挂载 Vue 应用...');
    console.log('[MicroFrontendMain] 微前端模式:', !!props?.container);
    console.log('[MicroFrontendMain] 传入的container:', props?.container);
    console.log('[MicroFrontendMain] 目标容器:', container);

    if (!container) {
      const availableElements = [
        document.getElementById('micro-frontend-main-app'),
        document.querySelector('#app'),
        document.body,
      ].filter(Boolean);

      console.error('[MicroFrontendMain] 容器查找失败，可用元素:', availableElements);
      throw new Error('[MicroFrontendMain] 找不到挂载容器！');
    }

    localApp.mount(container);
    console.log('✅ [MicroFrontendMain] Vue 应用挂载成功！');

    // 将局部变量赋值给全局变量
    app = localApp;

    // 等待路由准备完成后启动 qiankun
    console.log('🗺️ [MicroFrontendMain] 等待路由系统准备...');
    await router.isReady();
    console.log('✅ [MicroFrontendMain] 路由系统已准备完成！');

    // 如果有全局状态，同步到本地
    if (props?.getGlobalState) {
      const state = props.getGlobalState();
      console.log('[MicroFrontendMain] 同步全局状态到本地:', state);
    }

    console.log('[MicroFrontendMain] Mount process completed successfully');
  } catch (error) {
    console.error('[MicroFrontendMain] Error during mount:', error);
    throw error;
  }
}

export async function unmount() {
  console.log('[MicroFrontendMain] unmounted');

  if (app) {
    app.unmount();
    app = null;
  }

  if (history) {
    history = null;
  }

  router = null;
}

// 将生命周期方法挂载到 window 上供 qiankun 调用
if (window.__POWERED_BY_QIANKUN__) {
  (window as any).bootstrap = bootstrap;
  (window as any).mount = mount;
  (window as any).unmount = unmount;
}

// 独立运行时的逻辑
if (!window.__POWERED_BY_QIANKUN__) {
  console.log('[MicroFrontendMain] 运行在独立开发模式');
  console.log('[MicroFrontendMain] Document ready state:', document.readyState);

  // 确保DOM已经加载完成
  const initializeApp = () => {
    console.log('[MicroFrontendMain] initializeApp函数开始执行');

    const mockGlobalState = {
      user: {
        username: 'admin',
        nickname: '管理员（开发模式）',
        roles: ['admin'],
        permissions: ['*:*:*'],
      },
      token: `mock-token-${Date.now()}`,
      isLogin: true,
      permissions: ['*:*:*'],
      roles: ['admin'],
    };

    const mockMessageService = {
      broadcast: (event: string, data: any) => {
        console.log(`[MockMessageService] Broadcasting ${event}:`, data);
      },
      subscribe: (event: string, _callback: (data: any) => void) => {
        console.log(`[MockMessageService] Subscribed to ${event}`);
      },
      unsubscribe: (event: string) => {
        console.log(`[MockMessageService] Unsubscribed from ${event}`);
      },
    };

    console.log('[MicroFrontendMain] About to mount in standalone mode');
    console.log('🚨 [MicroFrontendMain] 开始独立模式挂载过程...');

    mount({
      routerBase: '/',
      getGlobalState: () => mockGlobalState,
      setGlobalState: (state: any) => {
        Object.assign(mockGlobalState, state);
        console.log('[MockGlobalState] State updated:', mockGlobalState);
      },
      messageService: mockMessageService,
    })
      .then(async () => {
        console.log('[MicroFrontendMain] Mount completed successfully');
        
        // 启动 qiankun 微前端框架（统一走全局启动器，且只启动一次）
        console.log('[MicroFrontendMain] 尝试启动 qiankun 微前端框架...');
        try {
          await waitForContainer();
          if ((window as any).isQiankunStarted) {
            console.log('[MicroFrontendMain] qiankun 已启动，跳过重复启动');
          } else if (typeof window.startQiankunWhenReady === 'function') {
            await window.startQiankunWhenReady();
            console.log('[MicroFrontendMain] ✅ 通过 startQiankunWhenReady 启动 qiankun 成功');
          } else {
            // 兜底：直接调用本地 startQiankun（理论上不会走到）
            await startQiankun();
            console.log('[MicroFrontendMain] ✅ 直接调用 startQiankun 启动成功');
          }
        } catch (error) {
          console.error('[MicroFrontendMain] ❌ qiankun 启动失败:', error);
        }
      })
      .catch((error) => {
        console.error('[MicroFrontendMain] Mount failed:', error);
      });
  };

  // 检查DOM是否已经准备好
  if (document.readyState === 'loading') {
    console.log('[MicroFrontendMain] DOM还在加载中，等待DOMContentLoaded事件');
    document.addEventListener('DOMContentLoaded', () => {
      console.log('[MicroFrontendMain] DOMContentLoaded事件触发，开始初始化应用');
      initializeApp();
    });
  } else {
    console.log('[MicroFrontendMain] DOM已经准备好，立即初始化应用');
    initializeApp();
  }
}
